﻿using System;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using YArchitech.Controls;

namespace YArchitech.HVAC
{
	public class ConnectDucs
	{
		public UIApplication UIApp { get; set; }

		public UIDocument UIDoc { get; set; }

		public ConnDuctFrom ConnForm { get; set; }

		public ConnectDucs(UIApplication uiApp, ConnDuctFrom form)
		{
			this.UIApp = uiApp;
			this.UIDoc = uiApp.ActiveUIDocument;
			this.ConnForm = form;
		}

		public bool Execute()
		{
			bool flag = false;
			new HYDuctConnect();
			Transaction transaction = null;
			for (;;)
			{
				RevitVersionFuncs.ClearSelection(this.UIDoc.Selection);
				transaction = new Transaction(this.UIDoc.Document, "风管连接");
				transaction.Start();
				try
				{
					ConnOperation connectOperation = OperationFactory.GetConnectOperation(this.ConnForm.DuctConn, this.UIDoc);
					if (connectOperation != null)
					{
						connectOperation.UIDoc = this.UIDoc;
						connectOperation.ConnForm = this.ConnForm;
						flag = connectOperation.Execute();
						if (!flag)
						{
							if (!string.IsNullOrEmpty(connectOperation.ErrorString))
							{
								YJKMessageBox.Show(connectOperation.ErrorString, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
							}
							if (transaction != null)
							{
								TransactionStatus status = transaction.GetStatus();
                                if ((int)status == 1)
								{
									transaction.RollBack();
								}
                                else if ((int)status == 5)
								{
									transaction.RollBack();
								}
							}
						}
						else
						{
							this.UIDoc.Document.Regenerate();
							transaction.Commit();
						}
					}
					else
					{
						YJKMessageBox.Show("没有找到合适的操作类！", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
					}
					continue;
				}
                catch (Autodesk.Revit.Exceptions.OperationCanceledException ex)
				{
					ex.ToString();
					transaction.Commit();
					if (transaction != null)
					{
						TransactionStatus status2 = transaction.GetStatus();
                        if ((int)status2 == 1)
						{
							transaction.RollBack();
						}
                        else if ((int)status2 == 5)
						{
							transaction.RollBack();
						}
					}
					if (this.ConnForm.isPicking)
					{
						this.ConnForm.isPicking = false;
						continue;
					}
				}
				catch (Exception)
				{
					YJKMessageBox.Show("连接失败！", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
					if (transaction != null)
					{
						TransactionStatus status3 = transaction.GetStatus();
                        if ((int)status3 == 1)
						{
							transaction.RollBack();
						}
                        else if ((int)status3 == 5)
						{
							transaction.RollBack();
						}
					}
					continue;
				}
				break;
			}
			return flag;
		}
	}
}
